package org.skydiveapp2;

import org.skydiveapp2.R;
import org.skydiveapp2.ui.InterfaceManager;
import org.skydiveapplibrary.ui.AuthenticationDialog;
import org.skydiveapplibrary.ui.ExportDestinationAdapter;
import org.skydiveapplibrary.ui.ImportSourceAdapter;
import org.skydiveapplibrary.ui.AuthenticationDialog.AuthenticationListener;
import org.skydiveapplibrary.util.DropBoxClient;
import org.skydiveapplibrary.util.ExportDestination;
import org.skydiveapplibrary.util.ExportTask;
import org.skydiveapplibrary.util.ImportSource;
import org.skydiveapplibrary.util.ImportTask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class ImportExportActivity extends Activity
{
	// Button Listeners
	private OnClickListener exportListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			exportClicked();
		}
	};
	private OnClickListener importListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			importClicked();
		}
	};
	private OnClickListener logoutListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			DropBoxClient.getInstance().logout(ImportExportActivity.this);
			setLogoutVisibiliity(false);
		}
	};

	// Check Authentication Tasks
	private class InitCheckAuthenticatedTask extends AsyncTask<Void, Void, Boolean>
	{
		@Override
		protected Boolean doInBackground(Void... arg0)
		{
			return DropBoxClient.getInstance().isAuthenticated(ImportExportActivity.this);
		}
		
		@Override
		protected void onPostExecute(Boolean result)
		{
			setLogoutVisibiliity(result);
		}
	}
	private class CheckAuthenticatedTask extends AsyncTask<Void, Void, Boolean>
	{
		private ProgressDialog progressDialog;
		
		@Override
		protected void onPreExecute()
		{
			progressDialog = ProgressDialog.show(new ContextThemeWrapper(ImportExportActivity.this, android.R.style.Theme_Holo_Dialog), "",
					ImportExportActivity.this.getString(R.string.authentication_progress));
		}
		
		@Override
		protected Boolean doInBackground(Void... arg0)
		{
			return DropBoxClient.getInstance().isAuthenticated(ImportExportActivity.this);
		}
		
		@Override
		protected void onPostExecute(Boolean result)
		{
			progressDialog.dismiss();
			if (result)
				doImportExport();
			else
				showAuthenticationDialog();
		}
	}
	// Authentication Dialog Listeners
	private AuthenticationListener authListener = new AuthenticationListener()
	{
		@Override
		public void authenticate(String userId, String password)
		{
			doAuthentication(userId, password);
		}
	};
	// Authentication Tasks
	private class AuthenticationTask extends AsyncTask<Void, Void, Boolean>
	{
		String userId;
		String password;
		ProgressDialog progressDialog;
		
		@Override
		protected void onPreExecute()
		{
			progressDialog = ProgressDialog.show(new ContextThemeWrapper(ImportExportActivity.this, android.R.style.Theme_Holo_Dialog), "",
					ImportExportActivity.this.getString(R.string.authentication_progress));
		}
		
		@Override
		protected Boolean doInBackground(Void... arg0)
		{
			return DropBoxClient.getInstance().authenticate(ImportExportActivity.this, userId, password);
		}
		
		@Override
		protected void onPostExecute(Boolean result)
		{
			progressDialog.dismiss();
			authenticationComplete(result);
		}
	};
	// custom import task
	private class HDImportTask extends ImportTask
	{
		public HDImportTask()
		{
			super(ImportExportActivity.this);
		}
		
		@Override
		protected void onPostExecute(Integer result)
		{
			super.onPostExecute(result);
		}
	}
	
	// flag indicating import/export
	private boolean isExport;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.import_export_view);
		
		initializeUI();
		
		overridePendingTransition(R.anim.fadein,
                R.anim.hold);
	}
	
	private void initializeUI()
	{
		// set subtitle text
		if (this.findViewById(R.id.tabletLayout) != null)
		{
			InterfaceManager.getInstance().configureTabletUI(this, 
					R.string.import_export_label);
		}
		else
		{
			InterfaceManager.getInstance().configurePhoneUI(this, 
					R.string.import_export_label);
		}
		
		Spinner exportSpinner = (Spinner) findViewById(R.id.ImportExportExportSpinner);
		exportSpinner.setAdapter(new ExportDestinationAdapter(this));
		
		Button exportButton = (Button) findViewById(R.id.ImportExportExportButton);
		exportButton.setOnClickListener(exportListener);

		Spinner importSpinner = (Spinner) findViewById(R.id.ImportExportImportSpinner);
		importSpinner.setAdapter(new ImportSourceAdapter(this));
		
		Button importButton = (Button) findViewById(R.id.ImportExportImportButton);
		importButton.setOnClickListener(importListener);
		
		Button logoutButton = (Button) findViewById(R.id.DropBoxLogoutButton);
		logoutButton.setOnClickListener(logoutListener);
		logoutButton.setVisibility(View.GONE);
	}
	
	
	@Override
	public void onResume()
	{
		super.onResume();
		
		// start is authenticated task to show/hide logout button
		InitCheckAuthenticatedTask task = new InitCheckAuthenticatedTask();
		task.execute();
	}
	
	private void setLogoutVisibiliity(boolean authenticated)
	{
		Button logoutButton = (Button) findViewById(R.id.DropBoxLogoutButton);
		logoutButton.setVisibility(authenticated ? Button.VISIBLE : Button.GONE);
	}
	
	private void exportClicked()
	{
		// set flag
		isExport = true;
		
		// get destination
		Spinner exportSpinner = (Spinner) findViewById(R.id.ImportExportExportSpinner);
		ExportDestination destination = (ExportDestination)exportSpinner.getSelectedItem();
		
		// check if authentication needed
		if (destination == ExportDestination.DropBox)
		{
			// check if authenticated
			CheckAuthenticatedTask task = new CheckAuthenticatedTask();
			task.execute();
		}
		else
		{
			// no authentication needed, just do export
			doExport();
		}
	}

	private void importClicked()
	{
		// set flag
		isExport = false;
		
		// get source
		Spinner importSpinner = (Spinner) findViewById(R.id.ImportExportImportSpinner);
		ImportSource source = (ImportSource)importSpinner.getSelectedItem();
		
		if (source == ImportSource.DropBox)
		{
			// check if authenticated
			CheckAuthenticatedTask task = new CheckAuthenticatedTask();
			task.execute();
		}
		else
		{
			doImport();
		}
	}
	
	private void showAuthenticationDialog()
	{
		// show authentication dialog
		AuthenticationDialog dialog = new AuthenticationDialog(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog), authListener);
		dialog.show();
	}
	
	private void doAuthentication(String userId, String password)
	{
		// init/execute task
		AuthenticationTask task = new AuthenticationTask();
		task.userId = userId;
		task.password = password;
		task.execute();
	}
	
	private void authenticationComplete(boolean success)
	{
		// show logout button
		setLogoutVisibiliity(success);
		
		if (success)
		{
			// continue
			doImportExport();
		}
		else
		{
			// show error
			Toast toast = Toast.makeText(this, R.string.authentication_invalid_error, Toast.LENGTH_SHORT);
			toast.show();
		}
	}
	
	private void doImportExport()
	{
		if (isExport)
			doExport();
		else
			doImport();
	}
	
	private void doExport()
	{
		// get destination
		Spinner exportSpinner = (Spinner) findViewById(R.id.ImportExportExportSpinner);
		ExportDestination destination = (ExportDestination)exportSpinner.getSelectedItem();
		
		// create export task
		ExportTask task = new ExportTask(this);
		task.execute(destination);
	}
	
	private void doImport()
	{
		// get source
		Spinner importSpinner = (Spinner) findViewById(R.id.ImportExportImportSpinner);
		ImportSource source = (ImportSource)importSpinner.getSelectedItem();

		// create import task
		ImportTask task = new HDImportTask();
		task.execute(source);
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.menu_back:		
			// finish
			close();
        	return true;
        
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		// set result
        Intent intent =  new Intent();
        setResult(RESULT_OK, intent);
		finish();
    	overridePendingTransition(R.anim.hold,
                R.anim.fadeout);
	}
}
